<?php

namespace addons\helper\library;

use fast\Http;

class Alisms
{
    private static $endpoint = 'https://dysmsapi.aliyuncs.com';

    private static function signatureUrl($accessKeyId, $accessKeySecret, $params)
    {
        $apiParams = array_merge(array(
            'SignatureMethod'  => 'HMAC-SHA1',
            'SignatureNonce'   => uniqid(mt_rand(0, 0xffff), true),
            'AccessKeyId'      => $accessKeyId,
            'SignatureVersion' => '1.0',
            'Timestamp'        => gmdate('Y-m-d\TH:i:s\Z'),
            'Format'           => 'JSON',
            "Action"           => "SendSms",
            'Version'          => '2017-05-25',
            "RegionId"         => "cn-hangzhou",
        ), $params);
        ksort($apiParams);
        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . self::encode($key) . "=" . self::encode($value);
        }
        $stringToSign = "GET&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));
        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
        $signature = self::encode($sign);

        $signatureUrl = self::$endpoint .'/?Signature=' . $signature.$sortedQueryStringTmp;

        return $signatureUrl;
    }
    /**
     * 阿里云发送短信
     *
     * @param string $accessKeyId       阿里云AccessKeyId
     * @param string $accessKeySecret   阿里云AccessKeySecret
     * @param string $mobile            要发送的手机号码
     * @param string $signName          阿里云短信签名
     * @param string $TemplateCode      阿里云短信模版ID
     * @param array $TemplateParam      模版变量
     * @param array $ext                扩展字段
     * @return void
     */
    public static function sendSms($accessKeyId, $accessKeySecret, $mobile, $signName, $TemplateCode, $TemplateParam = [], $ext = [])
    {
        $params = array(
            'PhoneNumbers'  => $mobile,             //手机号码
            'SignName'      => $signName,        //短信签名
            'TemplateCode'  => $TemplateCode,    //短信模板
            'TemplateParam' => $TemplateParam,   //模板参数
        );
        // 扩展字段：外部流水扩展字段
        $params['OutId'] = isset($ext['OutId']) ? $ext['OutId'] : ""; 
        // 扩展字段：上行短信扩展码，无特殊需要此字段的用户请忽略此字段。
        $params['SmsUpExtendCode'] = isset($ext['SmsUpExtendCode']) ? $ext['SmsUpExtendCode'] : "";

        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // 计算签名URl
        $signatureUrl = self::signatureUrl($accessKeyId, $accessKeySecret, $params);

        try {
            $result = Http::get($signatureUrl);
            return $result;
        } catch (\Exception $e) {
            return $e;
        }
    }
    private static function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }
}
